var express = require("express");
var router = express.Router();
var moment = require("moment");
var { getTree } = require("../utils/commonUtils");
const Permission = require("../db/model/permissionModel");
const { Op } = require("sequelize");
const User = require("../db/model/userModel");
const Role = require("../db/model/roleModel");

/**
 * @api {POST} /permission/add 权限添加
 * @apiDescription 权限添加
 * @apiName add
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiGroup Permission
 * @apiBody {Number} fid   权限父级id，0表示顶级
 * @apiBody {String} title  权限名称
 * @apiBody {String} index  路径
 * @apiBody {Number} sort  排序
 * @apiBody {String} mark  备注
 * @apiBody {String} icon  图标
 * @apiBody {Number} level 等级 0-一级 1-二级 2-按钮
 * @apiParamExample {json} Request-Example:
 *     {
 *        "fid": 0,
 *        "title": "系统管理",
 *        "index": "/system/list",
 *        "sort": 0,
 *        "mark": "系统管理",
 *        "icon": "sys",
 *        "level": 0
 *     }
 * @apiVersion 1.0.0
 */
router.post("/permission/add", async (req, res) => {
  try {
    let time = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    let result = await Permission.create({
      ...req.body,
      create_time: time,
      updated_time: time,
    });
    console.log("添加权限:", result);
    return res.json({ code: 200, message: "添加成功" });
  } catch (err) {
    return res.json({
      code: 500,
      message: "添加失败:" + err,
    });
  }
});

/**
 * @api {POST} /permission/edit 权限编辑
 * @apiDescription 权限编辑
 * @apiName edit
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiGroup Permission
 * @apiBody {Number} id=1                 权限id
 * @apiBody {Number} fid=0                权限父级id，0表示顶级
 * @apiBody {String} title="系统管理"       权限名称
 * @apiBody {String} index="/system/list"  路径
 * @apiBody {Number} sort=0               排序
 * @apiBody {String} mark="系统管理"       备注
 * @apiBody {Number} level=0              等级 0-一级 1-二级 2-按钮
 * @apiParamExample {json} Request-Example:
 *     {
 *        "id": 1,
 *        "fid": 0,
 *        "title": "系统管理",
 *        "index": "/system/list",
 *        "sort": 0,
 *        "mark": "系统管理",
 *        "icon": "sys",
 *        "level": 0
 *     }
 * @apiVersion 1.0.0
 */
router.post("/permission/edit", async (req, res) => {
  try {
    let { id } = req.body;
    if (!id) {
      return res.send({ code: 500, msg: "缺少id参数" });
    }
    let time = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    let result = await Permission.update(
      {
        ...req.body,
        updated_time: time,
      },
      {
        where: {
          id,
        },
      }
    );
    console.log("编辑权限:", result);
    return res.json({ code: 200, message: "编辑成功" });
  } catch (err) {
    return res.json({
      code: 500,
      message: "编辑失败:" + err,
    });
  }
});

/**
 * @api {POST} /permission/del 权限删除
 * @apiDescription 权限删除
 * @apiName del
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiGroup Permission
 * @apiBody {Number} id=1 权限id
 * @apiParamExample {json} Request-Example:
 *     {
 *        "id": 1
 *     }
 * @apiVersion 1.0.0
 */
router.post("/permission/del", async (req, res) => {
  try {
    let { id } = req.body;
    if (!id) {
      return res.send({ code: 500, msg: "缺少id参数" });
    }
    let result = await Permission.destroy({
      where: {
        id,
      },
    });
    console.log("删除权限:", result);
    return res.json({ code: 200, message: "删除成功" });
  } catch (err) {
    return res.json({
      code: 500,
      message: "删除失败:" + err,
    });
  }
});

/**
 * @api {POST} /permission/queryUserPermissions 查询用户权限
 * @apiDescription 查询用户权限
 * @apiName queryUserPermissions
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiGroup Permission
 * @apiBody {Number} user_id=1 权限id
 * @apiParamExample {json} Request-Example:
 *     {
 *        "user_id": 1
 *     }
 * @apiVersion 1.0.0
 */
router.post("/permission/queryUserPermissions", async (req, res) => {
  try {
    console.log("user info:", req.data);
    if (!req.data.user_id) {
      return res.send({ code: 500, msg: "缺少参数" });
    }
    // 查询用户信息
    let user = (await User.findByPk(req.data.user_id)).dataValues;
    // console.log("user", user);
    if (!user) {
      return res.send({ code: 500, msg: "用户数据异常" });
    }
    // 查询角色信息
    let role = (await Role.findByPk(user.role_id)).dataValues;
    // console.log("role", role);
    if (!role) {
      return res.json({ code: 200, message: "角色信息不存在!" });
    }
    if (!role.permission_ids) {
      return res.json({ code: 200, message: "暂无任何权限!" });
    }
    let permission_ids = role.permission_ids.split(",");
    // 查询权限
    let result;
    if (req.data.user_id == 1) {
      // 超级管理员查询所有权限，无视角色
      result = await Permission.findAll({
        order: [["sort", "DESC"]],
      });
    } else {
      result = await Permission.findAll({
        where: {
          id: {
            [Op.in]: permission_ids,
          },
        },
        order: [["sort", "DESC"]],
      });
    }

    if (!result || result.length == 0) {
      return res.json({ code: 200, message: "暂无任何权限!" });
    }
    let resData = result.map((o) => o.dataValues);
    // 组装权限
    let data = [];
    let formatData = resData.map((o) => {
      return {
        id: o.id,
        index: o.index,
        title: o.title,
        icon: o.icon,
        fid: o.fid,
        component: o.component,
        level: o.level,
      };
    });
    // console.log("formatData", formatData);
    getTree(0, formatData, data);

    return res.json({ code: 200, message: "查询成功", data });
  } catch (err) {
    return res.json({
      code: 500,
      message: "查询失败:" + err,
    });
  }
});

/**
 * @api {POST} /permission/queryRolePermissions 查询角色权限
 * @apiDescription 查询角色权限
 * @apiName queryRolePermissions
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiGroup Permission
 * @apiBody {Number} role_id=1 角色id
 * @apiParamExample {json} Request-Example:
 *     {
 *        "role_id": 1
 *     }
 * @apiVersion 1.0.0
 */
router.post("/permission/queryRolePermissions", async (req, res) => {
  try {
    let { role_id } = req.body;
    if (!role_id) {
      return res.send({ code: 500, msg: "缺少role_id参数" });
    }
    // 查询角色信息
    let role = (await Role.findByPk(role_id)).dataValues;
    // console.log("role", role);
    if (!role) {
      return res.send({ code: 500, msg: "角色数据异常" });
    }
    if (!role.permission_ids) {
      return res.json({ code: 200, message: "success", data: [] });
    }
    let permission_ids_arr = role.permission_ids
      .split(",")
      .map((o) => parseInt(o));
    // console.log("permission_ids_arr", permission_ids_arr);
    // 查询权限
    let result = await Permission.findAll({
      where: {
        id: {
          [Op.in]: permission_ids_arr,
        },
      },
      order: [["sort", "DESC"]],
    });
    if (!result || result.length == 0) {
      return res.json({ code: 200, message: "seccusee", data: [] });
    }
    let resData = result.map((o) => o.dataValues);
    let data = [];
    getTree(0, resData, data);

    // 查询所有权限
    let allResult = await Permission.findAll({
      order: [["sort", "DESC"]],
    });
    if (!allResult || allResult.length == 0) {
      return res.json({ code: 200, message: "success", data: [] });
    }
    let addResData = allResult.map((o) => o.dataValues);
    let allData = [];
    getTree(0, addResData, allData);

    let clearIds = [];
    // 遍历所有权限，如果
    allData.forEach((permission) => {
      if (permission_ids_arr.indexOf(permission.id) != -1) {
        if (permission.subs && permission.subs.length > 0) {
          permission.subs.forEach((two) => {
            if (permission_ids_arr.indexOf(two.id) == -1) {
              // 需要删除父级，因为不是全选
              if (clearIds.indexOf(permission.id) == -1) {
                clearIds.push(permission.id);
              }
            } else {
              if (two.subs && two.subs.length > 0) {
                two.subs.forEach((third) => {
                  if (permission_ids_arr.indexOf(third.id) == -1) {
                    // 需要删除二级，因为不是全选
                    if (clearIds.indexOf(two.id) == -1) {
                      clearIds.push(two.id);
                    }
                    if (clearIds.indexOf(permission.id) == -1) {
                      clearIds.push(permission.id);
                    }
                  }
                });
              }
            }
          });
        }
      }
    });

    // console.log("需要删除的id:", clearIds);

    return res.json({
      code: 200,
      message: "查询成功",
      data: permission_ids_arr.filter((o) => clearIds.indexOf(o) == -1),
    });
  } catch (err) {
    return res.json({
      code: 500,
      message: "查询失败:" + err,
    });
  }
});

/**
 * @api {POST} /permission/queryAllPermissions 查询所有权限
 * @apiDescription 查询所有权限
 * @apiName queryAllPermissions
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiGroup Permission
 * @apiVersion 1.0.0
 */
router.post("/permission/queryAllPermissions", async (req, res) => {
  try {
    // 查询权限
    let result = await Permission.findAll({
      order: [["sort", "DESC"]],
    });
    if (!result || result.length == 0) {
      return res.json({ code: 200, message: "暂无任何权限!" });
    }
    let resData = result.map((o) => o.dataValues);
    // 组装权限
    let data = [];
    // result.map(o=>o.children == [])
    getTree(0, resData, data);

    return res.json({ code: 200, message: "查询成功", data });
  } catch (err) {
    return res.json({
      code: 500,
      message: "查询失败:" + err,
    });
  }
});

module.exports = router;
